package cn.cookyfly.dailyreview.server;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import cn.cookyfly.dailyreview.client.RpcService;
import cn.cookyfly.dailyreview.server.utils.PropertiesDef;
import cn.cookyfly.dailyreview.server.utils.Utility;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RpcServiceImpl extends RemoteServiceServlet implements RpcService {

	private static final String LOGIN_KEY_USER_ID = "LOGIN_USER_ID";
	
	private static final long serialVersionUID = -4503749260950101391L;
	private static final Logger logger = Logger.getLogger(RpcServiceImpl.class.getName());

	@Override
	public String login(String loginId, String passwd) {
		if (StringUtils.isBlank(loginId) || StringUtils.isBlank(passwd)) {
			if (logger.isLoggable(Level.CONFIG))
				logger.config("Illegal arguments found while processing login: blank login ID or password");
			return "Login ID and password could not be blank";
		}
		if (Utility.shaDigest(loginId).equals(PropertiesDef.getLoginId()) && 
				Utility.shaDigest(passwd).equals(PropertiesDef.getLoginPasswd())) {
			HttpSession session = getThreadLocalRequest().getSession();
			session.setAttribute(LOGIN_KEY_USER_ID, loginId);
			if (logger.isLoggable(Level.FINE))
				logger.fine("User logged in. (user ID: " + loginId + ")");
			return "true";
		} else {
			if (logger.isLoggable(Level.FINE))
				logger.fine("User failed to login: incorrect login ID or password. (user name: " + 
						loginId + "), (password: " + passwd + ")");
			return "false";
		}
	}
	
	@Override
	public Boolean logout() {
		String userId = null;
		HttpSession session = getThreadLocalRequest().getSession(false);
		if (session != null) {
			if (logger.isLoggable(Level.FINE)) {
				userId = (String) session.getAttribute(LOGIN_KEY_USER_ID);
			}
			session.invalidate();
		}
		if (logger.isLoggable(Level.FINE))
			logger.fine("User logged out handly. (user ID: " + userId + ")");
		return true;
	}
	
	@Override
	public Boolean checkLogin() {
		HttpSession session = getThreadLocalRequest().getSession(false);
		if (session == null) {
			return false;
		} else {
			return (session.getAttribute(LOGIN_KEY_USER_ID) != null);
		}
	}
	
	@Override
	public Boolean saveReview(String[] reviewContent) {
		// TODO to be implemented
		return null;
	}
	
	public static void main(String[] args) {// TODO ---
		logger.info("Hi there~");
		logger.config("哈哈");
		logger.fine("呵呵 ");
		logger.severe("啊哦");
		System.out.println("Done.");
	}

}
